package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.PayVo;
import cn.wolfcode.feign.AliPayFeignApi;
import cn.wolfcode.feign.IntegralFeignApi;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {

    @Value("${pay.returnUrl}")
    private String returnUrl;
    @Value("${pay.notifyUrl}")
    private String notifyUrl;
    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private AliPayFeignApi aliPayFeignApi;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private IntegralFeignApi integralFeignApi;



    @GetMapping("/alipay")
    public Result<String> alipay(String orderNo, Integer type) {
        // 参数校验
        if (StringUtils.isEmpty(orderNo) && StringUtils.isEmpty(type + "")) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        // 校验orderNo是否存在
        OrderInfo orderInfo = orderInfoService.get(orderNo);
        if (orderInfo == null) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        String productName = orderInfo.getProductName();
        if(type.equals(OrderInfo.PAYTYPE_ONLINE)) {
            // 调用支付宝支付
            PayVo payVo = new PayVo();
            payVo.setOutTradeNo(orderNo);
            payVo.setTotalAmount(orderInfo.getSeckillPrice().toString());
            payVo.setSubject(productName);
            payVo.setBody(productName);
            payVo.setReturnUrl(returnUrl);
            payVo.setNotifyUrl(notifyUrl);
            // 调用支付服务
            Result<String> payResult = aliPayFeignApi.pay(payVo);
            // 返回result字符串
            if (payResult != null && !payResult.hasError()) {
                return Result.success(payResult.getData());
            }
        } else {
            // 调用积分支付
            orderInfoService.payIntegral(orderInfo);
        }
        return Result.success("");
    }


    @RequestMapping("/return_url")
    public void return_url(@RequestParam Map<String,String> params, HttpServletResponse response) throws IOException {
        Result<Boolean> result = aliPayFeignApi.rsaCheckV1(params);
        if (result != null && !result.hasError()) {
            // 如果延签成功
            if(result.getData()) {
                response.sendRedirect(frontEndPayUrl + params.get("out_trade_no"));
            }else {
                // 如果延签失败
                response.sendRedirect("http://localhost/50x.html");
            }
        }
    }

    @RequestMapping("/notify_url")
    public String notify_url(@RequestParam Map<String,String> params) {
        Result<Boolean> result = aliPayFeignApi.rsaCheckV1(params);
        if (result != null && !result.hasError()) {
            // 如果延签成功
            if(result.getData()) {
                orderInfoService.paySuccess(params);
                return "success";
            }
        }
        return "fail";
    }

    @RequestMapping("/refund")
    public Result<String> refund(String orderNo, HttpServletRequest request) {
        // 参数校验
        if (StringUtils.isEmpty(orderNo)) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        // 订单状态判断
        OrderInfo orderInfo = orderInfoService.get(orderNo);
        if (orderInfo == null) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        // 如果不是已付款,则不退款
        if (!OrderInfo.STATUS_ACCOUNT_PAID.equals(orderInfo.getStatus())) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        Integer payType = orderInfo.getPayType();
        if (payType.equals(OrderInfo.PAYTYPE_ONLINE)) {
            // 说明在线付款
            orderInfoService.refundAliPay(orderInfo);
        }else {
            // 说明积分支付
            orderInfoService.refundIntegral(orderInfo);
        }
        return Result.success("");
    }
}
